package open.panxiong.shared.activity

import android.app.ProgressDialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.lifecycle.MutableLiveData
import open.panxiong.shared.activity.router.RootComposable
import open.panxiong.shared.http.config.ConstConfig
import open.panxiong.shared.service.NanohttpdService
import open.panxiong.shared.service.binder.NanohttpdBinder
import open.panxiong.shared.util.getFileNameFromUri
import open.panxiong.shared.util.openBrowserViews
import open.panxiong.shared.util.showToast
import java.io.File


class MainActivity : ComponentActivity() {
    companion object {
        val nanohttpdServiceState: MutableLiveData<Boolean> = MutableLiveData<Boolean>(false)
        val currentServerUrl: MutableLiveData<String> =
            MutableLiveData<String>("http://localhost:${NanohttpdService.SERVER_PORT}/")
    }

    private var nanohttpdService: NanohttpdService? = null

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, binder: IBinder) {
            if (binder is NanohttpdBinder) {
                nanohttpdService = binder.service
            }
            nanohttpdService?.startNanohttpd()
        }

        override fun onServiceDisconnected(name: ComponentName) {
            nanohttpdService = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        enableEdgeToEdge()  // 启用全面屏
        setContent { RootComposable() }

        bindService(
            Intent(baseContext, NanohttpdService::class.java),
            serviceConnection,
            Context.BIND_AUTO_CREATE
        )

        onHandlerUserSharedFile(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()

        if (nanohttpdService != null) {
            unbindService(serviceConnection)
        }
    }

    /**
     * 处理用户在文件管理器等地方选择文件共享给 And Share 时的事件
     */
    private fun onHandlerUserSharedFile(bundle: Bundle?) {
        val progressDialog = ProgressDialog(this)
        progressDialog.setMessage("正在处理文件...")
        progressDialog.setCancelable(false)

        when (val intentAction = intent.action) {
            // 处理单个文件共享，根据系统版本选择合适的获取方法 用户选着发送或者直接点开文件显示打开方式时
            Intent.ACTION_SEND, Intent.ACTION_VIEW -> {
                val uri: Uri? = intent.getParcelableExtra(Intent.EXTRA_STREAM)
                uri?.let { u ->
                    progressDialog.show()
                    copyUriResourcesToDisk(u)
                }
            }
            // 处理多个文件共享，同样根据系统版本选择获取方法
            Intent.ACTION_SEND_MULTIPLE -> {
                val uris: List<Uri>? = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
                uris?.let { us ->
                    progressDialog.show()
                    for (u in us) {
                        copyUriResourcesToDisk(u)
                    }
                }
            }

            else -> {
                Log.i("MainActivity", "onHandlerUserSharedFile 不需要处理的类型 $intentAction")
            }
        }

        if (progressDialog.isShowing) {
            progressDialog.dismiss()
            showToast(this, "文件处理完成")
            if (!currentServerUrl.value.isNullOrEmpty()) {
                openBrowserViews(this, currentServerUrl.value!!)
            }
        }
    }

    /**
     * 保存Uri资源到磁盘
     */
    private fun copyUriResourcesToDisk(uri: Uri) {
        val dir = ConstConfig.getSharedFileDirectory(this)
        val name = getFileNameFromUri(this, uri)
        contentResolver.openInputStream(uri)?.use { inputStream ->
            File(dir, name).let { file ->
                file.outputStream().use { os ->
                    inputStream.copyTo(os)
                }
            }
        }
    }
}